package com.cdd.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.cdd.commonutils.R;
import com.cdd.servicebase.handler.SmartException;
import com.cdd.vod.service.VodService;
import com.cdd.vod.utils.ConstantVodUtil;
import com.cdd.vod.utils.InitVod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

    @Autowired
    private VodService vodService;
    // 上传视频到阿里云
    @PostMapping("uploadVideo")
    public R uploadVideo(MultipartFile file) {
        // 返回上传视频的ID
        String videoId = vodService.uploadVideo(file);
        return R.ok().data("videoId",videoId);
    }
    // 删除视频
    @DeleteMapping("deleteVod/{vodId}")
    public R deleteVod(@PathVariable String vodId) {
        try{
            DefaultAcsClient client = InitVod.initVodClient(ConstantVodUtil.KEYID, ConstantVodUtil.KEY_SECRET);
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(vodId);
            client.getAcsResponse(request);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            throw new SmartException(20001,"删除视频失败");
        }
    }
    // 删除多个视频
    @DeleteMapping("deleteVod-batch")
    public R deleteMoreVod(@RequestParam("vodIds") List<String> vodIds) {
        vodService.removeMoreVod(vodIds);
        return R.ok();
    }
    // 根据视频Id获取凭证
    @GetMapping("get-play-auth/{videoId}")
    public R getVideoPlayAuth(@PathVariable("videoId") String videoId) throws Exception {

        //获取阿里云存储相关常量
        String accessKeyId = ConstantVodUtil.KEYID;
        String accessKeySecret = ConstantVodUtil.KEY_SECRET;

        //初始化
        DefaultAcsClient client = InitVod.initVodClient(accessKeyId, accessKeySecret);

        //请求
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(videoId);

        //响应
        GetVideoPlayAuthResponse response = client.getAcsResponse(request);

        //得到播放凭证
        String playAuth = response.getPlayAuth();

        //返回结果
        return R.ok().message("获取凭证成功").data("playAuth", playAuth);
    }
}
